package org.lizar.controller.loader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FilePostForm {
	
	private Map<String,String> params=new HashMap<String,String>();
	
	private List<FileItem> items=new LinkedList<FileItem>();
	
	private String error_msg=null;
	
	public String getErrorMsg(){
		return this.error_msg;
	}
	
	public List<FileItem> getFiles(){
		return this.items;
	}
	
	public void setAllParamToAttr(EventLoader el){
		Iterator<Entry<String,String>> itr=params.entrySet().iterator();
		Entry<String,String> ent=null;
		for(;itr.hasNext();){
			ent=itr.next();
			el.setAttr(ent.getKey(), ent.getValue());
		}
	}
	
	/**
	 * 
	 * PostForm will return null, it index is not in items
	 * 
	 * */
	public FileItem getFileItem(int i){
		if(items.size()<i+1)return null;
		return items.get(i);
	}
	
	public List<FileItem> getFileItems(){
		return items;
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value 0
	 * 
	 * */
	public int getInt(String key){
		String v=params.get(key);
		if(v==null)return 0;
		else {
			try{
				return Integer.parseInt(v);
			}catch(Exception e){
				return 0;
			}
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value:defv
	 * 
	 * */
	public int getInt(String key,int defv){
		String v=params.get(key);
		if(v==null)return defv;
		else {
			try{
				return Integer.parseInt(v);
			}catch(Exception e){
				return defv;
			}
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value ""
	 * 
	 * */
	public String getStr(String key){
		String v=params.get(key);
		if(v==null)return "";
		else {
			return v.trim();
		}
	}
	
	public boolean getBool(String key){
		String v=params.get(key);
		if(v==null)return false;
		else {
			return Boolean.parseBoolean(v.trim());
		}
	}
	
	public boolean getBool(String key,boolean _default){
		String v=params.get(key);
		if(v==null)return _default;
		else {
			return Boolean.parseBoolean(v.trim());
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value:defv
	 * 
	 * */
	public String getStr(String key,String defv){
		String v=params.get(key);
		if(v==null)return defv;
		else {
			return v;
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value 0
	 * 
	 * */
	public long getLong(String key){
		String v=params.get(key);
		if(v==null)return 0;
		else {
			try{
				return Long.parseLong(v);
			}catch(Exception e){
				return 0;
			}
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value:defv
	 * 
	 * */
	public long getLong(String key,long _default){
		String v=params.get(key);
		if(v==null)return _default;
		else {
			try{
				return Long.parseLong(v);
			}catch(Exception e){
				return _default;
			}
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value 0
	 * 
	 * */
	public double getDouble(String key){
		String v=params.get(key);
		if(v==null)return 0;
		else {
			try{
				return Double.parseDouble(v);
			}catch(Exception e){
				return 0;
			}
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value:defv
	 * 
	 * */
	public double getDouble(String key,double _default){
		String v=params.get(key);
		if(v==null)return _default;
		else {
			try{
				return Double.parseDouble(v);
			}catch(Exception e){
				return _default;
			}
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value 0
	 * 
	 * */
	public float getFloat(String key){
		String v=params.get(key);
		if(v==null)return 0;
		else {
			try{
				return Float.parseFloat(v);
			}catch(Exception e){
				return 0;
			}
		}
	}
	
	/**
	 * 
	 * request.getParameter("parameter_name")
	 * 
	 * if result is null , will return default value:defv
	 * 
	 * */
	public float getFloat(String key,float _default){
		Object v=params.get(key);
		if(v==null)return _default;
		else {
			try{
				return Float.parseFloat(v.toString());
			}catch(Exception e){
				return _default;
			}
		}
	}
	
	public FilePostForm(EventLoader el,long max_file_size_byte){
		parse(el,max_file_size_byte);
	}
	
	private  void parse(EventLoader el,long max_file_size_byte){
		  try {
	            DiskFileItemFactory factory = new DiskFileItemFactory();
	            factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb
	            File cache_dir=new File(el.getRealPath("/WEB-INF/lizar/file_pos_form_cache"));
	            if(!cache_dir.exists())cache_dir.mkdirs();
	            factory.setRepository(cache_dir);// 设置缓冲区目录
	            ServletFileUpload upload = new ServletFileUpload(factory);
	            upload.setHeaderEncoding("utf-8");//解决文件乱码问题
	            upload.setSizeMax(max_file_size_byte);// 设置最大文件尺寸
	            List<FileItem> items = null;
	            try{
	            	items=upload.parseRequest(el.request());
	            }catch(SizeLimitExceededException e){
	            	error_msg=el.i18("upload.image.parse.failed");
	            	return;
	            }
	            if(items==null||items.isEmpty()){
	            		return;
	            }
	            Iterator<FileItem> itr = items.iterator();//所有的表单项
	            while (itr.hasNext()){
	                 FileItem item = (FileItem) itr.next();//循环获得每个表单项
	                 if(item.isFormField()){
	                	 System.out.println("name:"+item.getFieldName()+" value:"+new String(item.get(),"utf-8"));
	                	 params.put(item.getFieldName(), new String(item.get(),"utf-8"));
	                 }else{
	                	 if(item.getSize()>0){
	                		 this.items.add(item);
	                	 }
	                 }
	            }
	        } catch (Exception e) {
	        	error_msg=el.i18("server_error");
	            e.printStackTrace();
	            return;
	        }
	}
}
